package mya.mes.mdc.model.tag.convert;


import mya.mes.mdc.model.excel.ExcelTagAlarmDef;
import mya.mes.mdc.model.tag.AlarmTag;
import mya.mes.mdc.model.tag.MdcTag;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

class AlarmTagBuilder {


    public List<MdcTag> build(String shop, String area, List<ExcelTagAlarmDef> list) {
        List<AlarmTag> alarmTagList = buildAlarmTagList(shop, area, list);
        if (alarmTagList == null) {
            return null;
        }

        List<MdcTag> mdcTagList = alarmTagList.stream().map(alarmTag -> {
            MdcTag mdcTag = createMdcTagFromAlarmTag(alarmTag);
            mdcTag.shop = shop;
            mdcTag.area = area;
            return mdcTag;
        }).collect(Collectors.toList());
        return mdcTagList;
    }

    private List<AlarmTag> buildAlarmTagList(String shop, String area, List<ExcelTagAlarmDef> list) {
        List<AlarmTagTmp> tmpList = group(list);
        List<AlarmTag> alarmTagList = new ArrayList<>(tmpList.size());
        for (AlarmTagTmp tmp : tmpList) {
            AlarmTag alertDef = build(shop, area, tmp);
            alarmTagList.add(alertDef);
        }
        return alarmTagList;
    }

    private AlarmTag build(String shop, String area, AlarmTagTmp tmp) {
        AlarmTagParse alarmTagParse = new AlarmTagParse();
        AlarmTag alarmTag = alarmTagParse.convert(shop, area, tmp);
        return alarmTag;
    }

    //一个tag命令可以对应32个报警信息
    private List<AlarmTagTmp> group(List<ExcelTagAlarmDef> list) {
        List<AlarmTagTmp> tmpList = new ArrayList<>();
        AlarmTagTmp tmp = null;
        for (ExcelTagAlarmDef tagAlertDef : list) {
            if (tagAlertDef.rdbTag == null || tagAlertDef.rdbTag.isEmpty()) {
                if (tmp != null) {
                    tmp.list.add(tagAlertDef);
                } else {
                    System.out.println("tmp == null");
                }
                continue;
            }

            tmp = new AlarmTagTmp();
            tmp.tagName = tagAlertDef.rdbTag;
            tmp.list.add(tagAlertDef);
            tmpList.add(tmp);
        }
        return tmpList;
    }

    private MdcTag createMdcTagFromAlarmTag(AlarmTag alarmTag) {
        MdcTag mdcTag = new MdcTag();
        mdcTag.tagName = alarmTag.mdcTag;
        mdcTag.plcTagType = PlcTagType.DEF;
        mdcTag.tagPrefix = alarmTag.tagPrefix;
        mdcTag.tagIndex = alarmTag.tagIndex;
        mdcTag.alarmTag = alarmTag;
        mdcTag.viewTag = alarmTag.viewTag;
        if (mdcTag.viewTag != null) {
            mdcTag.viewTagName = mdcTag.viewTag.tagName;
        }
        return mdcTag;
    }
}
